package de.unibi.comet.tools;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

import de.unibi.comet.util.Log;

public class naive_matcher {

	public static void usage() {
		System.out.println("usage: naive_matcher <patterns>");
		System.out.println("   <patterns> file containing patterns");
		System.exit(1);
	}

	public static void main(String[] args) {
		if (args.length!=1) usage();
		FileInputStream patternFile = null;
		try {
			patternFile = new FileInputStream(args[0]);
		} catch (FileNotFoundException e) {
			System.out.println("File not found, sorry!");
			System.exit(1);
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(patternFile));
		ArrayList<String> l = new ArrayList<String>();
		try {
			while (true) {
				String line = br.readLine();
				if (line==null) break;
				StringTokenizer st = new StringTokenizer(line, "$", false);
				while (st.hasMoreTokens()) {
					String token = st.nextToken();
					if (token.length()>0) l.add(token);
				}
//				System.out.printf("line: %s\n",line);
			}
		} catch (IOException e) {
			System.out.println("I/O failure, sorry!");
			System.exit(1);
		}

		Log.getInstance().setTimingActive(true);
		Log.getInstance().setLogLevel(Log.Level.INSANE);
		//Log.getInstance().setLogLevel(Log.Level.EVERYTHING);
		
		br = new BufferedReader(new InputStreamReader(System.in));
		try {
			while (true) {
				String line = br.readLine();
				if (line==null) break;
				Log.getInstance().startTimer();
//				for i in xrange(len(s)):
//					pattern_nr=0
//					for p in l:
//						if i+len(p)>len(s): continue
//						match=True
//						for k in xrange(len(p)):
//							if (s[i+k]!=p[k]) and (p[k]!='?'):
//								match=False
//								break
//						if match:
//							#print 'output: found pattern %d ending at position %d'%(pattern_nr, i+len(p)-1)
//							#print 'Found match at %d'%(i+len(p)-1)
//							matches+=1
//						pattern_nr+=1
//				print 'output: found %d matches'%(matches)
				int matches=0;
				for (int i=0; i<line.length(); ++i) {
					for (String p : l) {
						if (i+p.length()>line.length()) continue;
						boolean match = true;
						for (int k=0; k<p.length(); k++) {
							if ((line.charAt(i+k)!=p.charAt(k)) && (p.charAt(k)!='?')) {
								match=false;
								break;
							}
						}
						if (match) {
							matches+=1;
							Log.getInstance().printNormal(String.format("m %d", i+p.length()-1));
						}
					}
				}
				Log.getInstance().printNormal(String.format("found %d matches", matches));
				
			}
		} catch (IOException e) {
			System.out.println("I/O failure, sorry!");
			System.exit(1);
		}
	}
}
